
import os
import json
import time
import math
from core.data_processor import DataLoader
from core.model import Model

import core.pyplot_utils as pltutils


def run():
    #读取配置文件
    configs = json.load(open('config.json', 'r'))
    #保存训练模型的文件夹如果没有就创建
    if not os.path.exists(configs['model']['save_dir']): os.makedirs(configs['model']['save_dir'])
    #加载和转换lstm模型数据
    data = DataLoader(
        os.path.join('data', configs['data']['filename']),#文件绝对路径 例/Users/magic/PycharmProjects/LSTM-Neural-Network-for-Time-Series-Prediction/data/testsh510500.csv
        configs['data']['train_test_split'],
        configs['data']['columns']    #数据列
    )

    model = Model()
    model.build_model(configs)
    x, y = data.get_train_data(
        seq_len=configs['data']['sequence_length'],
        normalise=configs['data']['normalise']
    )

    '''
	# in-memory training
	model.train(
		x,
		y,
		epochs = configs['training']['epochs'],
		batch_size = configs['training']['batch_size'],
		save_dir = configs['model']['save_dir']
	)
	'''
    # out-of memory generative training
    steps_per_epoch = math.ceil((data.len_train - configs['data']['sequence_length']) / configs['training']['batch_size'])
    model.train_generator(
        data_gen=data.generate_train_batch(
            seq_len=configs['data']['sequence_length'],
            batch_size=configs['training']['batch_size'],
            normalise=configs['data']['normalise']
        ),
        epochs=configs['training']['epochs'],
        batch_size=configs['training']['batch_size'],
        steps_per_epoch=steps_per_epoch,
        save_dir=configs['model']['save_dir']
    )

    x_test, y_test = data.get_test_data(
        seq_len=configs['data']['sequence_length'],
        normalise=configs['data']['normalise']
    )
    #多序列
    predictions = model.predict_sequences_multiple(x_test, configs['data']['sequence_length'], configs['data']['sequence_length'])
    #全序列
    predictions_full = model.predict_sequence_full(x_test, configs['data']['sequence_length'])
    #逐点序列
    predictions_point = model.predict_point_by_point(x_test)

    pltutils.plot_results_multiple(predictions, y_test, configs['data']['sequence_length'])
    pltutils.plot_results(predictions_full, y_test)
    pltutils.plot_results(predictions_point,y_test)


if __name__ == '__main__':
    run()